package util

import (
	"fmt"
	"log"
	"net/url"
	"os"
	"strings"
	"sync"

	"github.com/dlclark/regexp2"
)

func ParseAppData(html string) (appData string) {
	re, err := regexp2.Compile(`window.appData = JSON.parse\(decodeURIComponent\("(.*)"\)\);`, 0)
	// re, err := regexp2.Compile(`(\d+)-(\d+)`, 0)
	if err != nil {
		fmt.Println("compile ERROR:", err)
		return
	}

	match, _ := re.FindStringMatch(html)
	if match != nil {
		// fmt.Println("Match found:", match.GroupByNumber(1))
		appDataURL := match.GroupByNumber(1).String()
		appData, _ = url.QueryUnescape(appDataURL)
	} else {
		log.Println("Match not found:")
	}
	return
}

func WriteFile(msg string, title string, dirPath string, file string, wg *sync.WaitGroup) bool {
	defer func() {
		recover()
		if wg != nil {
			wg.Done()
		}
	}()

	if wg != nil {
		wg.Add(1)
	}

	err := os.MkdirAll(dirPath, 0755)
	if err != nil {
		log.Println("MkdirAll ERROR:", err)
		return false
	}

	filePath := fmt.Sprintf("%s%c%s", dirPath, os.PathSeparator, file)
	log.Printf("%s 持久化：%s\n", title, filePath)
	f, err := os.OpenFile(filePath, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		log.Printf("Write %s ERROR: %v\n", title, err)
		return false
	}
	f.WriteString(msg)
	f.Close()
	return true
}

func GenWellSigns(num int) string {
	signs := ""
	for i := 0; i < num; i++ {
		signs += "#"
	}
	return signs
}

func WithdrawCookie(cookieStr string) map[string]string {
	cookies := make(map[string]string, 3)
	arr := strings.Split(cookieStr, ";")
	if len(arr) > 0 {
		for _, arrI := range arr {
			cookieArr := strings.SplitN(arrI, "=", 2)
			if len(cookieArr) >= 2 {
				cookies[strings.TrimSpace(cookieArr[0])] = strings.TrimSpace(cookieArr[1])
			}
		}
	}
	return cookies
}
